import Vue from 'vue';
import VueRouter from 'vue-router';
import HomeView from '../views/HomeView.vue';
import MainLayout from '../layout/MainLayout.vue';
import PetsInfo from '../views/PetsInfo.vue';
import Chat from '../views/Chat.vue';
import PetsDiary from '../views/PetsDiary.vue';

Vue.use(VueRouter);

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/about',
    name: 'about',
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
  },
  {
    path: '/adduser',
    name: 'adduser',
    component: () => import(/* webpackChunkName: "about" */ '../views/AddUser.vue')
  },
  {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: "about" */ '../views/Login.vue')
  },
  {
    path: '/userinfo',
    name: 'userinfo',
    component: () => import(/* webpackChunkName: "about" */ '../views/UserInfo.vue')
  },
  {
    path: '/task',
    name: 'task',
    component: () => import(/* webpackChunkName: "about" */ '../views/Task.vue')
  },
  {
    path: '/',
    component: MainLayout,
    children: [
      {
        path: 'petsinfo',
        name: 'PetsInfo',
        component: PetsInfo
      },
      {
        path: 'chat',
        name: 'Chat',
        component: Chat
      },
      {
        path: 'petsdiary',
        name: 'PetsDiary',
        component: PetsDiary
      }
    ],
    meta: {
      requiresAuth: true
    }
  }
]
// 防止连续点击多次路由报错
let routerPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return routerPush.call(this, location).catch(err => err)
}

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
});

router.beforeEach((to, from, next) => {
  const isAuthenticated = !!localStorage.getItem('token'); // 根据实际的登录逻辑获取认证状态
  if (to.matched.some(record => record.meta.requiresAuth) && !isAuthenticated) {
    next('/login');
  } else {
    next();
  }
});

export default router;
